require 'opengl'
require 'm3g'
require 'pp'

class M3GWidget < Qt::GLWidget
  slots 'tackEvent()', 'tickEvent()'

  def initialize
    super
  end

  def initializeGL
    @wld = M3G::World.new

    cam = M3G::Camera.new
    cam.look_at 0,0,5, 0,0,0, 0,1,0
    @wld.active_camera = cam
    @wld.add_child cam

    bg = M3G::Background.new
    bg.color = 0x000000ff
    @wld.background = bg

    position_values = [1,-1,1,  1,1,1,  -1,-1,1,  -1,1,1,
                       -1,-1,-1,  -1,1,-1,  1,-1,-1,  1,1,-1,
                       -1,1,1,  -1,1,-1,  -1,-1,1,  -1,-1,-1]
    positions = M3G::VertexArray.new 12, 3, 2
    positions.set 0, 12, position_values
    scale = 1
    bias  = [0,0,0]

    texcoord_values =  [1,0, 1,1, 0,0, 0,1, 1,0, 1,1, 0,0, 0,1, 1,0, 0,0, 1,1, 0,1]
    texcoords = M3G::VertexArray.new 12, 2, 2
    texcoords.set 0, 12, texcoord_values
    texcoord_scale = 1
    texcoord_bias  = [0,0,0]

    vertices = M3G::VertexBuffer.new
    vertices.positions = positions, scale, bias
    vertices.tex_coords[0] = texcoords, texcoord_scale, texcoord_bias

    indices = [0,1,2,3, 2,3,4,5, 4,5,6,7, 6,7,0,1, 1,7,8,9, 0,10,6,11]
    strips  = [4,4,4,4,4,4]
    tris = M3G::TriangleStripArray.new indices, strips

    img, = M3G::Loader::load "kingyo.png"
    pp img
    tex = M3G::Texture2D.new img

    app = M3G::Appearance.new
    app.texture[0] = tex

    @cube = M3G::Mesh.new vertices, tris, app
    @wld.add_child @cube

    @g3d = M3G::Graphics3D::instance
  end

  def resizeGL width, height
    @g3d.viewport = 0,0,width,height
    @wld.active_camera.perspective = 45, width/(height*1.0), 0.1, 1000
  end

  def paintGL
    @g3d.render @wld
  end

  def mousePressEvent event
    @mousePos = event.pos 
  end

  def mouseReleaseEvent event
  end

 def mouseMoveEvent event
   moved = event.pos - @mousePos
   @cube.post_rotate 4,  0,1,0 if moved.x > 1
   @cube.post_rotate -4, 0,1,0 if moved.x < -1
   @mousePos = event.pos
   updateGL

 end

  def keyPressEvent event
    puts event.key.to_s + " is pressed"
    quit
  end

end

